import Back from '@/components/router/Back';
import TabMenus from '@/pages/components/tab-menus/TabMenus';
import { useRouter } from '@/router/hooks';
import { KnowMenu, SpecialtyType, WordType } from '@/types/know/know';
import { DownOutlined, RightOutlined, SearchOutlined, UpOutlined } from '@ant-design/icons';
import { Button, FloatButton, Input, message, Popconfirm } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import SubPageHeader from '../../components/SubPageHeader';
import SubPageContent from '../../components/SubPageContent';
import PaginationTable from '../../components/PaginationTable';
import knowService from '@/api/services/knowService';
import NewWordsModal from './components/NewWordsModal';
import { usePaginationTable } from '@/hooks/use-pagination/usePaginationTable';
import dayjs from 'dayjs';
import NewSynonymModal from './components/NewSynonymModal';
import '@/pages/know-gov/styles/know-gov.scss';
import { Ellipsis } from 'antd-mobile';
import ImportModal from './components/ImportModal';
import { AxiosProgressEvent } from 'axios';
import SubPageTabs from '../../components/SubPageTabs';
import PagesHeader from '@/components/pages-header';
import { SvgIcon } from '@/components/icon';
import TipDesc from '@/components/tipDesc/tipDesc';

const Entry = () => {
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [searchText, setSearchText] = useState('');
  const router = useRouter();
  const [newWordsModalVisible, setNewWordsModalVisible] = useState(false);
  const [newSynonymModalVisible, setSynonymModalVisible] = useState(false);
  const [importModalVisible, setImportModalVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [currentEditItem, setCurrentItem] = useState<SpecialtyType | WordType | null>(null);
  const [refreshSpecialty, setRefreshSpecialty] = useState(0);
  const [refreshSynonym, setRefreshSynonym] = useState(0);
  const [refreshSensitive, setRefreshSensitive] = useState(0);
  const [loading, setLoading] = useState(false);

  const deleteSpecialty = async (id: string) => {
    await knowService.delSpecialty(id);
    refreshData();
    message.success('删除专业词成功');
  };

  const deleteSynonym = async (id: string) => {
    await knowService.delSynonym(id);
    refreshData();
    message.success('删除同义词成功');
  };

  const deleteSensitiveWords = async (id: string) => {
    await knowService.delSensitiveWords(id);
    refreshData();
    message.success('删除敏感词成功');
  };

  const refreshData = async () => {
    switch (selectedIndex) {
      case 0:
        setRefreshSpecialty(refreshSpecialty + 1);
        break;
      case 1:
        setRefreshSynonym(refreshSynonym + 1);
        break;
      case 2:
        setRefreshSensitive(refreshSensitive + 1);
        break;
      default:
        break;
    }
  };

  const onEditClicked = (record: SpecialtyType) => {
    setIsEdit(true);
    setCurrentItem(record);
    console.log(selectedIndex);

    switch (selectedIndex) {
      case 0:
        setNewWordsModalVisible(true);
        break;
      case 1:
      case 2:
        setSynonymModalVisible(true);
        break;
      default:
        break;
    }
  };

  const specialtyColumns = [
    {
      title: '专业词',
      dataIndex: 'text',
      key: 'text',
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (createTime: string) => (
        <span>{dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      ),
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (updateTime: string) => (
        <span>{dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      ),
    },
    {
      title: '操作',
      width: '15%',
      dataIndex: 'actions',
      key: 'actions',
      render: (_, record: SpecialtyType) => (
        <div className="text-nowrap">
          <Button
            type="text"
            onClick={() => {
              onEditClicked(record);
            }}
          >
            <span className="flex items-center text-@brand-color">
              {' '}
              <SvgIcon icon="singleedit" size="20" className="mr-1"></SvgIcon>编辑
            </span>
          </Button>
          <Popconfirm
            placement="topLeft"
            title={'你确定删除吗？'}
            onConfirm={() => {
              deleteSpecialty(record._id);
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button type="text">
              <span className="flex items-center text-@error-color">
                {' '}
                <SvgIcon icon="message-ic3" size="20" className="mr-1" />
                删除
              </span>
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const synonymColumns = [
    {
      title: '标准词',
      dataIndex: 'subject',
      key: 'subject',
    },
    {
      title: '同义词',
      dataIndex: 'members',
      key: 'members',
      render: (members: string[]) => (
        <Ellipsis
          content={members.join(' / ')}
          rows={2}
          expandText={<DownOutlined />}
          collapseText={<UpOutlined />}
        />
      ),
    },
    {
      title: '同义词数',
      dataIndex: 'members',
      key: 'members',
      render: (members: string[]) => <span>{members?.length}</span>,
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (createTime: string) => (
        <span>{dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      ),
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (updateTime: string) => (
        <span>{dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      ),
    },
    {
      title: '操作',
      width: '15%',
      dataIndex: 'actions',
      key: 'actions',
      render: (_, record: SpecialtyType) => (
        <div className="text-nowrap">
          <Button
            type="text"
            onClick={() => {
              onEditClicked(record);
            }}
          >
            <span className="flex items-center text-@brand-color">
              {' '}
              <SvgIcon icon="singleedit" size="20" className="mr-1"></SvgIcon>编辑
            </span>
          </Button>
          <Popconfirm
            placement="topLeft"
            title={'你确定删除吗？'}
            onConfirm={() => {
              deleteSynonym(record._id);
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button type="text">
              <span className="flex items-center text-@error-color">
                {' '}
                <SvgIcon icon="message-ic3" size="20" className="mr-1" />
                删除
              </span>
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const sensitiveColumns = [
    {
      title: '敏感词类型',
      dataIndex: 'subject',
      key: 'subject',
      render: (subject: string) => <div className="text-nowrap">{subject}</div>,
    },
    {
      title: '相关词',
      dataIndex: 'members',
      key: 'members',
      render: (members: string[]) => (
        <Ellipsis
          content={members.join(' / ')}
          rows={2}
          expandText={<DownOutlined className="text-@brand-color" />}
          collapseText={<UpOutlined className="text-@brand-color" />}
        />
      ),
    },
    {
      title: <span className="text-nowrap">相关敏感词数</span>,
      dataIndex: 'members',
      key: 'members',
      render: (members: string[]) => <span>{members?.length}</span>,
    },
    {
      title: <span className="text-nowrap">添加时间</span>,
      dataIndex: 'createTime',
      key: 'createTime',
      render: (createTime: string) => (
        <span>{dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      ),
    },
    {
      title: <span className="text-nowrap">修改时间</span>,
      dataIndex: 'updateTime',
      key: 'updateTime',
      render: (updateTime: string) => (
        <span>{dayjs(updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      ),
    },
    {
      title: '操作',
      width: '15%',
      dataIndex: 'actions',
      key: 'actions',
      render: (_, record: SpecialtyType) => (
        <div className="text-nowrap">
          <Button
            type="text"
            onClick={() => {
              onEditClicked(record);
            }}
          >
            <span className="flex items-center text-@brand-color">
              {' '}
              <SvgIcon icon="singleedit" size="20" className="mr-1"></SvgIcon>
              编辑
            </span>
          </Button>
          <Popconfirm
            placement="topLeft"
            title={'你确定删除吗？'}
            onConfirm={() => {
              deleteSensitiveWords(record._id);
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button type="text">
              <span className="flex items-center text-@error-color">
                {' '}
                <SvgIcon icon="message-ic3" size="20" className="mr-1" />
                删除
              </span>
            </Button>
          </Popconfirm>
        </div>
      ),
    },
  ];

  const menus: KnowMenu[] = useMemo(() => {
    return [
      {
        key: 0,
        title: '专业词',
        firstTitle: '专业词',
        secondTitle: '专业词',
        children: (
          <PaginationTable
            refreshKey={refreshSpecialty}
            rowKey="_id"
            columns={specialtyColumns}
            searchText={searchText}
            api={knowService.getSpecialty}
          />
        ),
      },
      {
        key: 1,
        title: '同义词',
        firstTitle: '标准词',
        secondTitle: '同义词',
        children: (
          <PaginationTable
            refreshKey={refreshSynonym}
            rowKey="_id"
            columns={synonymColumns}
            searchText={searchText}
            api={knowService.getSynonym}
          />
        ),
      },
      {
        key: 2,
        title: '敏感词',
        firstTitle: '敏感词类型',
        secondTitle: '相关词',
        children: (
          <PaginationTable
            refreshKey={refreshSensitive}
            rowKey="_id"
            columns={sensitiveColumns}
            searchText={searchText}
            api={knowService.getSensitiveWords}
          />
        ),
      },
    ];
  }, [refreshSpecialty, refreshSynonym, refreshSensitive, searchText, selectedIndex]);

  const addSpecialty = async (words: string) => {
    try {
      const wordsArr = words.split('、');
      // 判断是否存在空格
      if (wordsArr.some((word) => word.trim() === '')) {
        message.error('请不要输入空格！');
        return;
      }
      const res = await knowService.addSpecialty(wordsArr);
      setNewWordsModalVisible(false);
      refreshData();
      message.success('新增专业词成功');
    } catch (error) {
      console.error('addSpecialty error ', error);
    }
  };

  const addSynonym = async (subject: string, words: string) => {
    try {
      const wordsArr = words.split('、');
      if (subject.trim() === '' || wordsArr.some((word) => word.trim() === '')) {
        message.error('请不要输入空格！');
        return;
      }
      await knowService.addSynonym({
        subject,
        members: words.split('、'),
      });
      setSynonymModalVisible(false);
      refreshData();
      message.success('新增同义词成功');
    } catch (error) {
      console.error('addSpecialty error ', error);
    }
  };

  const addSensitiveWords = async (subject: string, words: string) => {
    try {
      const wordsArr = words.split('、');
      if (subject.trim() === '' || wordsArr.some((word) => word.trim() === '')) {
        message.error('请不要输入空格！');
        return;
      }
      await knowService.addSensitiveWords({
        subject,
        members: words.split('、'),
      });
      setSynonymModalVisible(false);
      refreshData();
      message.success('新增敏感词成功');
    } catch (error) {
      console.error('addSensitiveWords error ', error);
    }
  };
  const updateSpecialty = async (words: string) => {
    try {
      const wordsArr = words.split('、');
      // 判断是否存在空格
      if (wordsArr.some((word) => word.trim() === '')) {
        message.error('请不要输入空格！');
        return;
      }
      await knowService.updateSpecialty(currentEditItem?._id!, words);
      setNewWordsModalVisible(false);
      setIsEdit(false);
      setCurrentItem(null);
      refreshData();
      message.success('更新成功');
    } catch (error) {
      console.error('updateSpecialty error ', error);
    }
  };

  const updateSynonym = async (words: string) => {
    try {
      const wordsArr = words.split('、');
      // 判断是否存在空格
      if (wordsArr.some((word) => word.trim() === '')) {
        message.error('请不要输入空格！');
        return;
      }
      const data = currentEditItem as WordType;
      await knowService.updateSynonym({
        ...data,
        members: words.split('、'),
      });
      setSynonymModalVisible(false);
      setIsEdit(false);
      setCurrentItem(null);
      refreshData();
      message.success('更新成功');
    } catch (error) {
      console.error('updateSpecialty error ', error);
    }
  };

  const updateSensitiveWords = async (words: string) => {
    try {
      const wordsArr = words.split('、');
      // 判断是否存在空格
      if (wordsArr.some((word) => word.trim() === '')) {
        message.error('请不要输入空格！');
        return;
      }
      const data = currentEditItem as WordType;
      await knowService.updateSensitiveWords({
        ...data,
        members: words.split('、'),
      });
      setSynonymModalVisible(false);
      setIsEdit(false);
      setCurrentItem(null);
      refreshData();
      message.success('更新成功');
    } catch (error) {
      console.error('updateSpecialty error ', error);
    }
  };

  const addNewWords = async (subject: string, words: string) => {
    setLoading(true);
    try {
      if (isEdit) {
        switch (selectedIndex) {
          case 0:
            await updateSpecialty(words);
            break;
          case 1:
            await updateSynonym(words);
            break;
          case 2:
            await updateSensitiveWords(words);
            break;
          default:
            break;
        }
      } else {
        switch (selectedIndex) {
          case 0:
            await addSpecialty(words);
            break;
          case 1:
            await addSynonym(subject, words);
            break;
          case 2:
            await addSensitiveWords(subject, words);
            break;
          default:
            break;
        }
      }
    } catch (error) {
    } finally {
      setLoading(false);
    }
  };

  const onAddWordsClicked = () => {
    switch (selectedIndex) {
      case 0:
        setNewWordsModalVisible(true);
        break;
      case 1:
      case 2:
        setSynonymModalVisible(true);
        break;
      default:
        break;
    }
  };

  const onImportFile = async (
    formData: FormData,
    onUploadProgress: (event: AxiosProgressEvent) => void,
  ) => {
    try {
      switch (selectedIndex) {
        case 0:
          await knowService.importSpecialtyFile(formData, onUploadProgress);
          break;
        case 1:
          await knowService.importSynonymFile(formData, onUploadProgress);
          break;
        case 2:
          await knowService.importSensitiveFile(formData, onUploadProgress);
          break;
        default:
          break;
      }
      message.success('导入成功');
      setImportModalVisible(false);
      refreshData();
    } catch (error) {
      console.error('importWords error ', error);
    }
  };

  const getTemplateUrl = () => {
    const type =
      selectedIndex === 0 ? 'specialization' : selectedIndex === 1 ? 'synonym' : 'censored';
    ///openapi/v1/terms/template/download
    return `/openapi/v1/terms/template/download?type=${type}`;
  };

  return (
    <div className="flex h-full flex-col overflow-hidden">
      <PagesHeader>
        词条管理
        <TipDesc title='维护业务领域的标准术语库或关键短语库' />
      </PagesHeader>
      {/* <SubPageHeader
        menus={menus}
        // title="词条管理"
        isRootDisplay={false}
        selectedIndex={selectedIndex}
        onChangeIndex={(index) => setSelectedIndex(index)}
        onSearchTextChanged={setSearchText}
      >
        <Button onClick={onAddWordsClicked} className="mr-2">
          新增{menus[selectedIndex].title}
        </Button>
        <Button onClick={() => setImportModalVisible(true)} className="mr-2">
          导入
        </Button>
      </SubPageHeader> */}
      <SubPageTabs
        menus={menus}
        title="词条管理"
        isRootDisplay={false}
        selectedIndex={selectedIndex}
        onChangeIndex={(index) => setSelectedIndex(index)}
        onSearchTextChanged={setSearchText}
      >
        <div
          className="ml-[15px] flex  h-[32px] cursor-pointer items-center justify-center rounded-md border  !border-@brand-color px-3 !text-@brand-color"
          onClick={onAddWordsClicked}
        >
          <SvgIcon icon="message-ic13" size="15" className="mr-1" />
          新增{menus[selectedIndex].title}
        </div>
        <div
          className="ml-[15px] flex h-[32px] cursor-pointer items-center justify-center rounded-md border  !border-@brand-color px-3 !text-@brand-color"
          onClick={() => setImportModalVisible(true)}
        >
          <SvgIcon icon="message-ic14" size="15" className="mr-1" />
          导入
        </div>
      </SubPageTabs>

      <SubPageContent menus={menus} selectedIndex={selectedIndex} />
      <NewWordsModal
        destroyOnClose
        defaultText={(currentEditItem as SpecialtyType)?.text}
        placeholder="输入专业词汇，多个词请使用顿号（、）隔开"
        title={`${isEdit ? '编辑' : '新增'}${menus[selectedIndex].title}`}
        open={newWordsModalVisible}
        loading={loading}
        onCancel={() => {
          setLoading(false);
          setIsEdit(false);
          setCurrentItem(null);
          setNewWordsModalVisible(false);
        }}
        onConfirm={(words) => addNewWords('', words)}
      />
      <NewSynonymModal
        style={{ maxWidth: '90%', minWidth: '40%', height: '40%' }}
        defaultText={(currentEditItem as WordType)?.members?.join('、')}
        defaultSubject={(currentEditItem as WordType)?.subject}
        placeholder="输入专业词汇，多个词请使用顿号（、）隔开"
        title={`${isEdit ? '编辑' : '新增'}${menus[selectedIndex].title}`}
        isEdit={isEdit}
        firstTitle={menus[selectedIndex].firstTitle}
        secondTitle={menus[selectedIndex].secondTitle}
        open={newSynonymModalVisible}
        loading={loading}
        onCancel={() => {
          setLoading(false);
          setSynonymModalVisible(false);
          setIsEdit(false);
          setCurrentItem(null);
        }}
        onClose={() => {
          setLoading(false);
          setCurrentItem(null);
          setSynonymModalVisible(false);
          setIsEdit(false);
        }}
        onConfirm={addNewWords}
      />
      <ImportModal
        open={importModalVisible}
        onConfirm={onImportFile}
        // type={}
        templateUrl={getTemplateUrl()}
        title="导入词条"
        onCancel={() => {
          setImportModalVisible(false);
        }}
      />
    </div>
  );
};

export default Entry;
